package com.springboot.base.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/api/login")
public class LoginController {

    @Resource
    @Qualifier("alipayClient")
    private AlipayClient alipayClient;


    /**
     * 支付宝通过授权码登录
     * @param authCode
     * @return
     */
    @RequestMapping("alipay")
    public AlipaySystemOauthTokenResponse alipayLogin(@RequestParam("authCode") String authCode) {
        try {
            AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();

            // 授权方式：authorization_code，表示换取使用用户授权码code换取授权令牌access_token
            request.setGrantType("authorization_code");
            // 填入前端传入的授权码authCode，用户对应用授权后得到。本参数在 grant_type 为 authorization_code 时必填
            request.setCode(authCode);
            AlipaySystemOauthTokenResponse response = alipayClient.certificateExecute(request);
            if(response.isSuccess()){
                System.out.println("调用成功");
            } else {
                System.out.println("调用失败");
            }
            return response;
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return null;
    }
}
